import SubTitle from '@/pages/OrderModule/common/components/SubTitle';
import Typography from '@/pages/OrderModule/common/components/Typography';
import { Radio, Space, Alert, Form, Button, Input, Select, Popconfirm, message } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { useState, useEffect, useRef, useMemo, createElement } from 'react';
import orderUtils from '@/pages/OrderModule/common/utils/order';
import { getOrderIdsOp } from '../../../services';
import { cloneDeep } from 'lodash';

/**
 * 订单范围 单选框
 * @param {object} props
 * @param {object} props.wrapStyle 外层样式
 */
function OrderAreaRadioGroup(props) {
  const { wrapStyle = {}, orderList, searchForm, selectKeys, states = [], otherRulesFunc, updateShowNumer, title = '仅限待审核、异常状态的自发订单', ...args } = props || {};

  const [type, setType] = useState('a');
  const [loading, setLoading] = useState(false);

  const stageParams = useRef({});
  const form = Form.useFormInstance(); // 获取当前上下文正在使用的 Form 实例
  const addStrategyWatch = Form.useWatch('addStrategy', form);

  // const isSearch = useMemo(()=>{
  //   const params = cloneDeep(searchForm);
  //   const { orderTypeMap } = params;
  //   if(orderTypeMap && typeof orderTypeMap == 'object'){
  //     const values = Object.values(orderTypeMap);
  //     if(values.filter(item=>item)?.length){
  //       return true;
  //     }
  //   }
  //   delete params.orderTypeMap;
  //   const arr = Object.keys(params), len = arr.length;
  //   for(let i = 0; i < len; i++){
  //     const currentValue = params[arr[i]], dataType = typeof currentValue;
  //     if(currentValue){//真值
  //       if(Array.isArray(currentValue) && !currentValue?.length){
  //         delete params[arr[i]];
  //       }
  //     }else if(['string', 'undefined', 'object'].includes(dataType)){//假值
  //       delete params[arr[i]];
  //     }
  //   }

  //   console.log(searchForm, params)
  //   delete params.pageNum;
  //   delete params.pageSize;
  //   delete params.timeType;
  //   delete params.sortBy;
  //   delete params.isOrderTypeOr;
  //   delete params.sortType;
  //   return Boolean(Object.keys(params)?.length);
  // }, [searchForm])

  useEffect(() => {
    console.log('props.form', props)
    if (type == 'a') {
      if (!stageParams.current.numObj1) {
        const sourceData = orderUtils.commonFilterOrder({
          states,
          otherRulesFunc,
          sourceData: orderUtils.getSelectedRowData(selectKeys, orderList),
        }),
          numObj = orderUtils.statisticsNumbers(states, sourceData);
        stageParams.current.numObj1 = numObj;
      }
      updateShowNumer?.(stageParams.current.numObj1, selectKeys);
    } else {
      getOrderIds();
    }
  }, [type])

  //临时兼容已经铺设联调的部分
  const formatNumberObj = (numberObj) => {
    const fieldsMap = {
      auditCount: 10,
      shippingCount: 20,
      exceptionCount: 30,
      shippedCount: 40,
      cancelledCount: 50,
      totalCount: 'total'
    }
    const arr = Object.keys(numberObj);
    arr.map(item => {
      numberObj[fieldsMap[item]] = numberObj[item];
    })
    // console.log(numberObj)
    return numberObj;
  }

  const getOrderIds = async () => {
    let orderIds = stageParams.current.orderIds || [];
    if (!stageParams.current.numObj2) {
      setLoading(true);
      const { data, success } = await getOrderIdsOp(searchForm);
      setLoading(false);
      if (success && data?.orderList?.length) {
        const { orderList, ...numberObj } = data || {};
        orderIds = orderList;
        stageParams.current.numObj2 = formatNumberObj(numberObj);
        stageParams.current.orderIds = orderList;
      }
    }
    updateShowNumer?.(stageParams.current.numObj2, orderIds);
  }

  const key = 'prefixx'

  const Cprice = (props) => { // 采购价组件
    const {Component, props: _props,  ...rest} = props
    return (
      <>
      {createElement(Component,{ ...rest, ..._props})}元
      </>
    )
  }

  const saveItem = () => {
    args?.saveFormula() // 调用父组件传递的保存方法
  }

  return (
    <div style={wrapStyle}>
      <SubTitle symbol as="s2" title="修改方式" wrapStyle={{ marginBottom: 16 }} />
      <Radio.Group {...args}>
        <Space direction="vertical">
          <Radio value={1}>普通商品替换
            <div>
              {
                props.renderInnerInputArr1.map((item, index) => (
                  // react原生方法创建dom
                  <Form.Item key={`formItem-${index}`} {...item}>
                    {createElement(item.Component, item.props)}
                  </Form.Item>
                ))
              }
            </div>
          </Radio>
          <Radio value={2}>按卖家备注换商品
            <div style={{ marginTop: 5}}>
              <Alert message="卖家备注格式：商品编码1+商品编码2*2=商品编码3*3 ，商品编码4=商品编码5 +商品编码6*2 （=左边是被替换的商品，右边是替换的商品）（有多个公式，逗号隔开）
如果备注里含有其他无关备注，请前后分别用@@隔开。比如：备注内容1@@商品编码1+商品编码2*2=商品编码3*3  @@备注内容2
注意：如果商品sku数不一样，则商品ID会全部复用原商品ID，建议换货是一对一的商品编码" type="error" />
            </div>
          </Radio>
          <Radio value={3}>按公式换商品
            <div style={{marginBottom: 11, marginTop: 5}}>
              <Alert message="替换公式：商品编码1+商品编码2*2=商品编码3*3 ，商品编码4=商品编码5 （=左边是被替换的商品，右边是替换的商品）" type="error" />
            </div>
            {
              props.renderInnerInputArr3.map((item, index) => (
                <Form.List name="users" key={index}>
                  {(fields, { add, remove }) => (
                    <>
                      {fields.map(({ key, name, ...restField }) => (
                        <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                          {/* <Form.Item
                            {...restField}
                            name={[name, 'first']}
                            rules={[{ required: true, message: '请输入商品编码替换公式' }]}
                            style={{width: '120px'}}
                          >
                              <Select
                                style={{ width: 120 }}
                                allowClear
                                options={[
                                  {
                                    value: 'jack',
                                    label: 'Jack',
                                  },
                                  {
                                    value: 'Yiminghe',
                                    label: 'yiminghe',
                                  },
                                ]}
                              />
                          </Form.Item> */}
                          <Form.Item
                            {...restField}
                            name={[name, 'first2']}
                            rules={[{ required: addStrategyWatch == 3 ? true : false, message: '请输入商品编码替换公式' }]}
                            style={{width: '420px'}}
                            // dependencies={[['users', name, 'first']]}
                          >
                            <Input maxLength={50} placeholder="请输入商品编码替换公式" />
                            {/* {(aaa) => {
                              console.log('aaa', aaa)
                              return (
                                <Input placeholder="请输入商品编码替换公式" />
                              )
                            }} */}
                          </Form.Item>
                          {/* <MinusCircleOutlined onClick={() => remove(name)} /> */}
                          <a style={{fontSize: 12}} onClick={() => {
                            if(form.getFieldValue('users')[name]?.first2) {
                              saveItem()
                            } else {
                              message.warning('请输入换货公式')
                            }
                          }}>保存</a>
                          <Popconfirm
                            title="确认删除吗?"
                            onConfirm={() => {
                              console.log(fields, 'Form.List显示数据', form.getFieldValue('users'))
                              // 输入框有内容时，才调用删除接口
                              const val = form.getFieldValue('users')[name]
                              remove(name)
                              val && saveItem()
                            }}
                            okText="确定"
                            cancelText="取消"
                          >
                            <a style={{fontSize: 12}}>删除</a>
                          </Popconfirm>
                          
                        </Space>
                      ))}
                      <Form.Item>
                        <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                          添加公式
                        </Button>
                      </Form.Item>
                    </>
                  )}
                </Form.List>
              ))
            }
          </Radio>
          <Radio value={4}>按卖家备注换自定义商品
            <div style={{ marginTop: 5}}> 
              <Alert message="
卖家备注格式：J：XXX自定义商品名称
替换公式：J：为供应商页面的“门店备注”，订单商品的供应商会取该门店备注映射的供应商；商品名称：然后将单商品的订单自动换成“XXX商品名称”的自定义商品。
只支持单sku商品的订单，比如A商品2件，可以换成某个自定义商品2件" type="error" />
            </div>
            {
              props.renderInnerInputArr4.map((item, index) => 
              {
                const {Component, ...rest} = item
                console.log('rest---', rest)
                return (
                  // react原生方法创建dom
                  <Form.Item key={`formItem-${index}`} {...item}>
                    {/* {createElement(Component,{ ...item.props, ...rest})}元 */}
                    <Cprice {...item} />
                  </Form.Item>
                )
              })
            }
          </Radio>
        </Space>
      </Radio.Group>
    </div>
  );
}
export default OrderAreaRadioGroup;
